<template>
    <el-card class="card-one" shadow="never">
      <div class="contract-header"> 
        <div class="header-text">合同编号：{{ base_info.basic?.contract_no }}<el-icon @click="onCopy(base_info.basic?.contract_no)" color="#FF6B00" style="width: 13px;height: 13px;margin-left: 10px;cursor: pointer;"><CopyDocument /></el-icon></div>
        <div class="btn-list">
          <div v-for="(item, index) in sopBtnList" :key="index">
            <el-button class="btn-detail" plain v-show="base_info.button.includes(item.id)" @click=contractBtn(item.id)>{{ item.val }}</el-button>
          </div>
        </div> 
      </div>
      <el-divider />
      <div class="contract-footer">
        <div class="footer-left">
            <div class="footer-text">{{ base_info.basic?.title }}</div>
            <div class="tips-right">{{base_info.basic?.cust_type == 2?'企业':'个人'}}</div>
        </div>
        <div class="footer-detail">
            <div v-for="(item, index) in view_info" :key="index">
                <div v-if="item.content == 'contract_amount'">
                  <div class="detail-title">{{item.name}}</div>
                  <div class="detail-text detail-color">{{ base_info.basic[item.content]?'￥'+numFormat(base_info.basic[item.content]):'--' }}</div>
                </div>
                <div v-else>
                  <div class="detail-title">{{item.name}}</div>
                  <div class="detail-text">{{ base_info.basic[item.content]||'--' }}</div>
                </div>
            </div>
        </div>
      </div>
    </el-card>
    <el-card shadow="never">
        <el-tabs @tab-change="switchTab" v-model="activeName">
            <el-tab-pane :label="item.label" :name="item.value" v-for="item in tabList" :key="item.value"></el-tab-pane>
        </el-tabs>
        <div class="content" v-show="activeName == '1'">
          <div class="item_title"><span class="title_icon"></span>基本信息</div>
          <div class="basic-text">
            <div class="basic-content" v-for="(item,index) in basic_text" :key="index">
              <div v-if="item.content == 'business_license'">
                <div class="text-title">{{ item.name }}</div>
                <el-image class="basic-img" :src="base_info.info[item.content]" :preview-src-list="[base_info.info[item.content]]"></el-image>
              </div>
              <div v-else>
                <div class="text-title">{{ item.name }}</div>
                <div class="text-detail">{{ base_info.info[item.content] ? base_info.info[item.content] : '--' }}</div>
              </div>
            </div>
          </div>
          <div class="item_title"><span class="title_icon"></span>参数信息</div>
          <div class="basic-text">
            <div class="basic-content" v-for="(item,index) in base_info.info?.contract_template_params" :key="index">
              <div class="text-title">{{ item.name }} </div>
              <div class="text-detail">{{ item.current_val+(item.suffix?item.suffix:'') }}</div>
            </div>
          </div>
        </div>
        <div v-show="activeName == '2'">
          <el-table
            :data="base_info.audit"
            stripe
            tooltip-effect="light"
            :header-cell-style="{ background: '#fafafa', color: '#909399' }"
            header-row-class-name="table_header_title"
          >
            <el-table-column label="编号">
              <template #default="scope">
                <div>{{scope.row.audit_no || '--'}}</div>
              </template>
            </el-table-column>
            <el-table-column label="当前审批节点">
              <template #default="scope">
                <div>{{scope.row.audit_node == 1 ? '待提交' : scope.row.audit_node == 2 ? '一级审批' : scope.row.audit_node == 3 ? '二级审批' : scope.row.audit_node == 4 ? '已撤回' : '已驳回'}}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <div>{{scope.row.operate_type == 1 ? '提交审批' : scope.row.operate_type == 2 ? '撤回' : scope.row.operate_type == 3 ? '驳回' : '通过'}}</div>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template #default="scope">
                <div>{{scope.row.remark || '--'}}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作者">
              <template #default="scope">
                <div>{{scope.row.operator_uid_name || '--'}}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作时间">
              <template #default="scope">
                <div>{{scope.row.created_at || '--'}}</div>
              </template>
            </el-table-column>
            <template slot="empty">
              <el-empty image="/static/noData.png" description="暂无数据"></el-empty>
            </template>
          </el-table>
        </div>
        <ZWDeletdialog ref="submitRef" @submit="submit" />
        <Dialog :appDialog="appDialog">
          <div class="dialog">
            <div v-if="isShow == 6 || isShow == 7">
              <div>{{ isShow == 6 ? '您确定要通过该审批吗？' : '您确定要驳回该审批吗？请填写驳回原因：' }}</div>
              <el-input class="remark" v-model="auditParams.remark" :rows="3" type="textarea" placeholder="备注"></el-input>
            </div>
            <div v-if="isShow == 4">
              <div>您可以复制以下链接发送给客户签约：</div>
              <div>{{ linkData }}<el-icon @click="onCopy(linkData)" color="#FF6B00" style="width: 13px;height: 13px;margin-left: 10px;cursor: pointer;"><CopyDocument /></el-icon></div>
            </div>
          </div>
    </Dialog>
    </el-card>
</template>
  
  <script lang="ts" setup>
  import { ref, reactive, computed, onActivated, onMounted, onUnmounted } from 'vue'
  import { contractDetail, submitContract, withdrawContract, signContract, auditContract, inviteContract, viewEc , generateEc, realName } from '@/api/salesleads/contractmanagement/contract'
  import { useRoute, useRouter } from 'vue-router'
  import useClipboard from 'vue-clipboard3'
  import { ElMessage } from 'element-plus'
  import { numFormat } from '@/utils/utils'
  import ZWDeletdialog from '@/components/ZWDeletdialog.vue'
  import Dialog from '@/components/Dialog.vue'
  import { downloadEC } from '@/api/ecommerce/storeManage'
  import {downFile} from '@/utils/utils'


  const { toClipboard } = useClipboard()
  const route = useRoute()
  const router = useRouter()
  const activeName = ref('1')
  const isShow = ref(0)
  const submitRef = ref(null)
  const linkData = ref()
  const tabList = reactive([
    { label: '基本信息', value: '1' },
    { label: '审批记录', value: '2' }
  ])
  const auditParams = reactive({
    id: 0,
    audit_type: 1,//1-通过 2-驳回
    remark: ''
  })
  const base_info = ref({
    basic: {},
    info: {},
    audit: [],
    audit_weiwork: [],
    button: []
  })
  const sopBtnList = reactive([
  { id: 1, val: '提交审批', authCode: 'SUBMIT_APPROVAL' },
  { id: 2, val: '编辑', authCode: 'EDIT_CONTRACT' },
  { id: 3, val: '撤回', authCode: 'WIDTHDRAW' },
  { id: 4, val: '签约邀请', authCode: 'SINGIN_INVIT' },
  { id: 5, val: '签署合同', authCode: 'SIGN_CONTRACT' },
  { id: 6, val: '通过', authCode: 'ADOPT' },
  { id: 7, val: '驳回', authCode: 'REJECT' },
  { id: 8, val: '生成电子合同', authCode: 'GENER_CONTRACT' },
  { id: 9, val: '客户实名认证', authCode: 'REAL_NAME' },
  { id: 10, val: '查看', authCode: 'VIEW_CONTRACT' },
  { id: 11, val: '下载合同', authCode: 'DOWNLOAD_CONTRACT' }
    ])
  const view_info = reactive([
    { name: '合同金额', content: 'contract_amount' },
    { name: '合同客户', content: 'cust_name' },
    { name: '所属员工', content: 'belong_staff_name' },
    { name: '审批状态', content: 'audit_state_name' },
    { name: '合同状态', content: 'state_name'},
    { name: '有效期', content: 'effect'},
    { name: '签约日期', content: 'sign_time'}
  ])
  const basic_text = reactive([
    { name: '统一社会信用代码', content: 'uscc'},
    { name: '法人姓名', content: 'legal_person'},
    { name: '业务联系人', content: 'business_contact'},
    { name: '业务联系人身份证', content: 'business_id_card'},
    { name: '营业执照', content: 'business_license'},
    { name: '合同模板', content: 'contract_template_name'},
  ])
  const cancelHandel = () => {
  appDialog.visible = false
  }
  const submitHandel = () => {
    isShow.value == 6 ? auditParams.audit_type = 1 : auditParams.audit_type = 2
    auditContract(auditParams).then((res: any) => {
      ElMessage.success('审批成功')
      appDialog.visible = false
      getDetail(auditParams.id)
    })
  }
  const appDialog: any = reactive({
    visible: false,
    title: '通过审批提醒',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
  })
  const contractBtn = async (id: any) => {
    switch (id) {
      case 1: //提交审批
        submitRef.value.appDialog.title = '提交审批提醒'
        submitRef.value.content = '您确定要提交审批吗？'
        submitRef.value.appDialog.visible = true
        break
      case 2: // 编辑
        router.push(`/salesleads/salesmanagement/contractmanagement/addContract?id=${auditParams.id}&pageType=edit&type=edit`)
        break
      case 3: //撤回
        submitRef.value.appDialog.title = '撤回审批提醒'
        submitRef.value.content = '您确定要撤回该审批吗？'
        submitRef.value.appDialog.visible = true
        break
      case 4: //签约邀请
        getInvite(auditParams.id)
        break
      case 5: //签署合同
        submitRef.value.appDialog.title = '签署合同提醒'
        submitRef.value.content = '您确定要签署该合同吗？'
        submitRef.value.appDialog.visible = true
        break
      case 6: // 通过
        appDialog.title = '通过审批提醒'
        auditParams.remark = ''
        appDialog.visible = true
        break
      case 7: // 驳回
        appDialog.title = '驳回审批提醒'
        auditParams.remark = ''
        appDialog.visible = true
        break
      case 8: //生成电子合同
        getgenerateEc(auditParams.id)
        break
      case 9: //客户实名认证
        getRealName(auditParams.id)
        break
      case 10: //查看
        getViewEc(auditParams.id)
        break
      case 11: //下载合同
        await downloadFn(auditParams.id)
      break
    }
    isShow.value = id
  }

const downloadFn = async (id: any) => {
  const {contract_url} = await downloadEC({id})
  if(contract_url){
    downFile(contract_url, '')
  }
}

const getViewEc = (val: any) => {
  viewEc({id: val}).then((res: any) => {
    window.open(res.viewpdf_url)
  })
}
const getRealName = (val: any) => {
  realName({id: val}).then((res: any) => {
    ElMessage.success('客户实名认证成功')
    getDetail(auditParams.id)
  })
}
const getgenerateEc = (val: any) => {
  generateEc({id: val}).then((res: any) => {
    ElMessage.success('生成电子合同成功')
    getDetail(auditParams.id)
  })
}
const getInvite = async(val: any) => {
  const res = await inviteContract({id: val})
  linkData.value = res.link_url
  appDialog.title = '签约邀请'
  appDialog.isHiddenFoot = true
  appDialog.visible = true
}
const submit = async() => {
  const params = auditParams.id
  switch (isShow.value) {
    case 1:
      await submitContract({ id: params })
      ElMessage.success('提交审批成功')
      submitRef.value.appDialog.visible = false
      getDetail(auditParams.id)
      break
    case 3:
     await withdrawContract({ id: params })
      ElMessage.success('撤回审批成功')
      submitRef.value.appDialog.visible = false
      getDetail(auditParams.id)
      break
    case 5:
      await signContract({ id: params })
      ElMessage.success('签署合同成功')
      submitRef.value.appDialog.visible = false
      getDetail(auditParams.id)
      break
  }
}
  const getDetail = (val: any) => {
      contractDetail({id: val}).then((res: any) => {
          base_info.value = res
      })
  }
  const onCopy = async (v: any) => {
    try {
      await toClipboard(v)
      ElMessage.success('复制成功')
    } catch (e) {
      ElMessage.error('复制失败')
    }
  }
  const switchTab = () => {
  }
  onMounted(() => {
      auditParams.id = route.query.id
      getDetail(auditParams.id)
  })
  </script>
  <style lang="scss" scoped>
  .card-one {
    margin-bottom: 16px;
    .contract-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .header-text {
            font-size: 16px;
            font-weight: 500;
            color: #33302D;
        }
        .btn-list {
          display: flex;
          .btn-detail {
            margin: 0 5px;
          }
        }
    }
    .contract-footer {
        display: flex;
        .footer-left {
            width: 20%;
            border-right: 1px solid #EAEAEA;
            display: flex;
            justify-content: space-between;
            .footer-text {
              font-size: 18px;
              font-weight: 500;
              color: #33302D;
              line-height: 20px;
            }
            .tips-right {
              white-space: nowrap;
              color: #FF6B00;
              text-align: center;
              width: 43px;
              height: 20px;
              line-height: 20px;
              background: #FFF1ED;
              border-radius: 2px;
              margin-right: 6px;
            }
        }
        .footer-detail {
            width: 80%;
            display: flex;
            justify-content: space-around;
            .detail-title {
                font-size: 14px;
                text-align: center;
                font-weight: 400;
                color: #696969;
                line-height: 20px;
            }
            .detail-text {
                margin-top: 14px;
                text-align: center;
                font-size: 18px;
                font-weight: 500;
                color: #33302D;
                line-height: 24px;
            }
            .detail-color {
              color: #FF6B00
            }
        }
    }
  }
  .content {
    padding: 0 24px 24px 24px;
    .item_title {
      font-size: 14px;
      line-height: 1.125rem;
      font-family: STHeitiSC-Medium, STHeitiSC;
      font-weight: 500;
      color: #33302d;
      margin-bottom: 8px;
      .title_icon {
        display: block;
        height: 1.125rem;
        width: 0.1875rem;
        background: #ff6b00;
        float: left;
        margin-left: -0.9375rem;
      }
    }
    .basic-text {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      .basic-content {
        width: 50%;
        line-height: 45px;
        .text-title {
          display: inline-block;
          margin-right: 12px;
          width: 130px;
          text-align: right;
          font-size: 14px;
          font-weight: 400;
          color: #969696;
          vertical-align: top;
        }
        .basic-img {
          width: 110px;
          height: 110px;
        }
        .text-detail {
          display: inline-block;
          font-size: 14px;
          font-weight: 400;
          color: #33302D;
        }
      }
    }
  }
  .dialog {
    padding: 15px 10px;
    .remark {
      margin-top: 15px;
    }
  }
  </style>
  